import router, { asyncRoutes } from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
// import { getToken } from '@/utils/auth' // get token from cookie
// import { Message } from 'element-ui'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

// 白名单
const whiteList = ['/login', '/404']

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  if (store.state.user.token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      if (!store.state.user.userInfo.userId) {
        const res = await store.dispatch('user/getUserInfo')
        console.log('menu', res)

        const newAsyncRoutes = asyncRoutes.filter(item => res.includes(item.children[0].name))

        // 解决404
        newAsyncRoutes.push({ path: '*', redirect: '/404', hidden: true })

        console.log(newAsyncRoutes)

        // 访问页面
        router.addRoutes(newAsyncRoutes)
        // 显示菜单
        store.commit('menu/setMenu', newAsyncRoutes)

        console.log(to.path.split('/')[1], 789)
        console.log(to.path.substring(1), 789)

        if (res.includes(to.path.split('/')[1])) {
          // 解决白屏
          next({ path: to.path, replace: true })
        } else {
          // 重新登录不拥有当前跳转页面权限时，跳转至首页
          next('/dashboard')
        }
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

// 设置标题
router.beforeEach((to, form, next) => {
  // document.title = getPageTitle(router.history.pending.meta.title)
  document.title = getPageTitle(to.meta.title)
  next()
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
